using RGuang.PlathformCtrl.FSM;
using UnityEngine;

namespace RGuang.PlathformCtrl
{
    public class PlayerController : MonoBehaviour
    {
        [SerializeField] VoidEventChannel levelClearedEventChannel;
        public AudioSource VoicePlayer;
        PlayerGroundDetector groundDetector;
        PlayerInput playerInput;
        Rigidbody rigidBody;
        public bool Victory { get;private set; }
        public bool CanAirJump { get; set; }//空中跳
        public bool IsGrounded => groundDetector.IsGrounded;//true着地
        public bool IsFalling => rigidBody.velocity.y < 0f && !IsGrounded;//true下落
        public float MoveSpeed => Mathf.Abs(rigidBody.velocity.x);
        private void Awake()
        {
            groundDetector = GetComponentInChildren<PlayerGroundDetector>();
            playerInput = GetComponent<PlayerInput>();
            rigidBody = GetComponent<Rigidbody>();
            VoicePlayer = GetComponentInChildren<AudioSource>();
        }

        private void OnEnable()
        {
            levelClearedEventChannel.AddListener(OnLevelCleared);
        }
        private void OnDisable()
        {
            levelClearedEventChannel.RemoveListener(OnLevelCleared);
            
        }
        private void Start()
        {
            playerInput.EnableGameplayInputs();
        }

        void OnLevelCleared()
        {
            Victory = true;
        }

        public void OnDefeated()
        {
            playerInput.DisableGameplayInputs();
            rigidBody.velocity = Vector3.zero;
            rigidBody.useGravity = false;
            rigidBody.detectCollisions = false;
            GetComponent<StateMachine>().SwitchState(typeof(PlayerState_Defeated));
        }
        public void Move(float speed)
        {
            if (playerInput.Move)
            {
                transform.localScale = new Vector3(playerInput.AxisX, 1f, 1f);
            }
            SetVelocityX(speed * playerInput.AxisX);
        }
        public void SetVelocity(Vector3 velocity)
        {
            rigidBody.velocity = velocity;
        }
        public void SetVelocityX(float velocityX)
        {
            rigidBody.velocity = new Vector3(velocityX, rigidBody.velocity.y);
        }
        public void SetVelocityY(float velocityY)
        {
            rigidBody.velocity = new Vector3(rigidBody.velocity.x, velocityY);
        }
        public void SetUseGravity(bool enable)
        {
            rigidBody.useGravity = enable;
        }
    }

}
